#pragma once

#include <iostream>
#include <string>
#include <cstdlib>
#include <unistd.h>
#include <cassert>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <fcntl.h>

const std::string pathname = "./Common.hpp";
const int proj_id = 0x234;
const int size = 4096;
const std::string filename = "fifo";
key_t GetKey()
{
    key_t key = ftok(pathname.c_str(), proj_id);
    if (key < 0)
    {
        std::cerr << "errno:" << errno << ",errnostring:" << std::strerror(errno) << std::endl;
        exit(-1);
    }
    return key;
}

int CreatShmHelper(key_t key, int flag)
{
    int shmid = shmget(key, size, flag); //共享内存也有权限也是需要设置的
    // EXCL保证创建时如果存在就会失败
    if (shmid < 0)
    {
        std::cerr << "errno:" << errno << ",errnostring:" << std::strerror(errno) << std::endl;
        exit(2);
    }
    return shmid;
}

int CreatShm(key_t key)
{
    return shmget(key, size, IPC_CREAT | IPC_EXCL | 0644); //共享内存也有权限也是需要设置的
}

int GetShm(key_t key)
{
    return shmget(key, size, IPC_CREAT); //共享内存也有权限也是需要设置的
}

//为1创建成功
bool MakeFifo()
{
    int n = mkfifo(filename.c_str(), 0666);
    if (n < 0)
    {
        std::cerr << "errno:" << errno << ",errstring" << strerror(errno) << std::endl;
        return 0;
    }
    std::cout << "mkfifo success..." << std::endl;
    return 1;
}
